import JSEncrypt from 'jsencrypt'
import { defineStore } from 'pinia'
import userMenuStore from '@/store/common/menu'
import { TOKEN_NAME } from '@/config/constants'
import { doLogin, loginOut } from '@/api/common/auth'
import { loginForm } from '@/model/common/login/model'

const useUserStore = defineStore({
  id: 'star_user',
  state: () => ({
    id: '',
    username: '',
    isSidebarCompact: false
  }),
  actions: {
    async RESET_STATE () {
      this.$reset()
    },
    async login (data: loginForm, publicKey: string) {
      const { loginName, password } = data

      const jse = new JSEncrypt()
      jse.setPublicKey(publicKey)

      return doLogin({
        ...data,
        loginName: String(jse.encrypt(loginName)),
        password: String(jse.encrypt(password))
      }).then((data) => {
        const { userId, userName, token } = data
        this.id = userId
        this.username = userName
        localStorage.setItem(TOKEN_NAME, token)
      })
    },
    async logout () {
      return loginOut().then(() => {
        this.RESET_STATE()
        userMenuStore().RESET_STATE()
        localStorage.removeItem(TOKEN_NAME)
      })
    },
    updateConfig (paylod: {key: string; value: any}) {
      const { key, value } = paylod
      switch (key) {
        case 'isSidebarCompact':
          this.isSidebarCompact = value
          break
        default:
          break
      }
    }
  },
  persist: true
})

export default useUserStore
